<?php

namespace App\Models;

use App\Models\Traits\Timestamp;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserCouponUseRecord extends Model
{
    use HasFactory,Timestamp;

    protected $fillable = ['id','user_id','coupon_id','admin_id','amount','price','desc'];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id');
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class,'coupon_id');
    }

    public function admin()
    {
        return $this->belongsTo(User::class,'admin_id');
    }

    protected static function booted()
    {
        static::created(function ($model){

            $userCoupon = UserCoupon::find($model->coupon_id);

            $userCoupon->value = $userCoupon->value - $model->price;
            $userCoupon->save();

        });
    }
}
